package com.bugbuff.dubbo.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bugbuff.common.enums.LevelType;
import com.bugbuff.common.mapper.*;
import com.bugbuff.common.pojo.*;
import com.bugbuff.common.utils.UserThreadLocal;
import com.bugbuff.dubbo.server.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class TestSoulService {

    @Autowired
    private SoulQuestionnaireMapper soulQuestionnaireMapper;

    @Autowired
    private SoulReportMapper soulReportMapper;

    @Autowired
    private SoultQuestionMapper soultQuestionMapper;

    @Autowired
    private SoulOptionsMapper soulOptionsMapper;

    @Autowired
    private SoulConclusionMapper soulConclusionMapper;

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 查询问卷列表
     * @return
     */
    public List<QuestionnaireVo> queryQuestionnaireList() {
        //获取当前登录用户
        User user = UserThreadLocal.get();
        //查询问卷信息
        List<Questionnaire> questionnaires = soulQuestionnaireMapper.selectList(null);
        //遍历问卷信息，封装返回前台的实体类
        List<QuestionnaireVo> questionnaireVoList=new ArrayList<>();
        for (Questionnaire questionnaire : questionnaires) {
            QuestionnaireVo questionnaireVo=new QuestionnaireVo();
            questionnaireVo.setId(questionnaire.getId());
            questionnaireVo.setCover(questionnaire.getCover());
            //获取是否锁住
            questionnaireVo.setIsLock(this.queryIsLock(user.getId(),questionnaire.getLevel()));
            questionnaireVo.setLevel(questionnaire.getLevel()==1? LevelType.Level_1.toString():(questionnaire.getLevel()==2? LevelType.Level_2.toString():LevelType.Level_3.toString()));
            questionnaireVo.setName(questionnaire.getName());
            questionnaireVo.setStar(questionnaire.getStar());
            //填充试题信息
            questionnaireVo.setQuestions(this.queryQuestionsById(questionnaire.getId()));
            //获取用户的最新报告id
            questionnaireVo.setReportId(this.queryReportIdByUserId(user.getId(),questionnaire.getLevel()));
            questionnaireVoList.add(questionnaireVo);
        }
        return questionnaireVoList;
    }

    /**
     * 根据问卷id,查询对应的问题
     * @param id
     * @return
     */
    private List<TestQuestion> queryQuestionsById(String id) {
        /*LambdaQueryWrapper<TestQuestion> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(TestQuestion::getNid,id);
        List<TestQuestion> testQuestionList = testQuestionMapper.selectList(queryWrapper);*/
        List<TestQuestion> testQuestionList = soultQuestionMapper.queryQuestionsById(id);
        return testQuestionList;
    }

    /**
     * 查询问卷是否锁住
     * @param userId
     * @param level
     * @return
     */
    private Integer queryIsLock(Long userId, Integer level) {
        if(level==1){
            //初级问卷直接给用户填写，不能锁住
            return 0;
        }
        Integer newLevel=this.getLevelRange(level);
        LambdaQueryWrapper<SoulReport> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(SoulReport::getUid,userId).eq(SoulReport::getLevel,newLevel);
        Integer count = soulReportMapper.selectCount(queryWrapper);
        if(count>0){
            //低级别的问卷已经做过,可以解锁
            return 0;
        }
        return 1;
    }

    /**
     * 获取比当前问卷级别低的问卷级别
     * @param level
     * @return
     */
    private Integer getLevelRange(Integer level) {
        List<Integer> levelList=new ArrayList<>();
        if(level==2){
            //中级的应查询用户是否做过初级测试
            return 1;
        }
        //高级的应查询用户是否做过中级测试
        return 2;
    }

    /**
     * 查询用户的最近报告id
     * @param id
     * @param level
     * @return
     */
    private String queryReportIdByUserId(Long id, Integer level) {
        LambdaQueryWrapper<SoulReport> queryWrapper=new LambdaQueryWrapper<>();
        //按时间降序排序
        queryWrapper.eq(SoulReport::getUid,id).eq(SoulReport::getLevel,level).orderByDesc(SoulReport::getCreated);
        try {
            //查询该用户的报告
            List<SoulReport> soulReports = soulReportMapper.selectList(queryWrapper);
            if(CollUtil.isNotEmpty(soulReports)){
                //返回最近的一次报告id
                return String.valueOf(soulReports.get(0).getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 提交问卷功能
     * @param answers
     * @return
     */
    public String submitQuestion(List<AnswerVo> answers) {
        if(CollUtil.isEmpty(answers)){
            log.info("提交的问卷内容为空");
            return null;
        }
        //获取当前用户id
        User user = UserThreadLocal.get();
        //根据题目id查询题目所属的问卷信息
        Questionnaire questionnaire=this.queryByQusetionId(answers.get(0).getQuestionId());
        //根据答案计算得分，生成报告
        SoulReport soulReport=new SoulReport();
        //用户id
        soulReport.setUid(user.getId());
        //问卷id
        soulReport.setQuestionnaireId(questionnaire.getId());
        //问卷级别
        soulReport.setLevel(questionnaire.getLevel());
        soulReport.setConclusion(this.getConclusionId(answers));
        //保存报告到数据库中
        soulReportMapper.insert(soulReport);
        return String.valueOf(soulReport.getId());
    }

    /**
     * 计算问卷中问题答案的总得分，生成鉴定结果
     * @param answers
     * @return
     */
    private Integer getConclusionId(List<AnswerVo> answers) {
        //总得分
        int score=0;
        for (AnswerVo answer : answers) {
            //根据试题id,和选项id，查询对应的得分
            /*QueryWrapper<Options> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("qid",answer.getQuestionId()).eq("id",answer.getOptionId());*/
            Options option = soulOptionsMapper.selectByQuestionIdAndOptionId(answer.getQuestionId(),answer.getOptionId());
            if(ObjectUtil.isNotEmpty(option)){
                score+=option.getScore();
            }
        }
        //判断结果类型
        if(score<21){
            return 1;
        }else if(score>=21 && score<40){
            return 2;
        }else if(score>=41 && score<55){
            return 3;
        }else{
            return 4;
        }
    }

    /**
     * 根据题目id查询题目所属的问卷信息
     * @param questionId
     * @return
     */
    private Questionnaire queryByQusetionId(String questionId) {
        //先根据试题id查询所属的问卷id
        QueryWrapper<TestQuestion> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.eq("id",questionId).select("nid");
        TestQuestion testQuestion = soultQuestionMapper.selectOne(queryWrapper1);
        //再根据问卷id,查询问卷信息
        QueryWrapper<Questionnaire> queryWrapper2=new QueryWrapper<>();
        queryWrapper2.eq("id",testQuestion.getNid()).select("id","level");
        Questionnaire questionnaire = soulQuestionnaireMapper.selectOne(queryWrapper2);
        return questionnaire;
    }

    /**
     * 查看测灵魂结果
     * @param reportId
     * @return
     */
    public ReportVo queryReport(String reportId) {
        //获取当前登录用户
        User user = UserThreadLocal.get();
        QueryWrapper<SoulReport> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("id",reportId);
        //查询测试报告结果
        SoulReport soulReport = soulReportMapper.selectOne(queryWrapper);
        //根据鉴定结果类型字段查询鉴定结果的具体信息
        QueryWrapper<SoulConclusion> condition=new QueryWrapper<>();
        condition.eq("id",soulReport.getConclusion());
        SoulConclusion soulConclusion = soulConclusionMapper.selectOne(condition);
        //封装返回前台的实体类
        ReportVo reportVo=new ReportVo();
        //测试结果封面
        reportVo.setCover(soulConclusion.getCover());
        //鉴定结果
        reportVo.setConclusion(soulConclusion.getConclusion());
        //维度
        reportVo.setDimensions(this.getDimensions(soulConclusion.getDimensions()));
        //相似用户
        reportVo.setSimilarYou(this.querySimilarUsers(soulReport.getConclusion(),user.getId()));
        return reportVo;
    }

    /**
     * 查询鉴定结果相似的用户
     * @param conclusionId
     * @param userId
     * @return
     */
    private List<UserInfoVo> querySimilarUsers(Integer conclusionId, Long userId) {
        //先查询鉴定结果一样的用户id
        List<SoulReport> soulReports=soulReportMapper.querySimilarUsers(conclusionId,userId);
        List<Object> uids = CollUtil.getFieldValues(soulReports, "uid");
        List<UserInfo> userInfos=new ArrayList<>();
        List<UserInfoVo> userInfoVoList=new ArrayList<>();
        if(CollUtil.isNotEmpty(uids)){
            //获取用户信息
            userInfos = userInfoService.queryUserInfoByUserIdList(uids);
        }
        //遍历用户信息，封装vo对象
        for (UserInfo userInfo : userInfos) {
            UserInfoVo userInfoVo=new UserInfoVo();
            userInfoVo.setId(userInfo.getUserId());
            userInfoVo.setAvatar(userInfo.getLogo());
            userInfoVoList.add(userInfoVo);
        }
        return userInfoVoList;
    }

    /**
     * 加工维度数据
     * @param dimensions
     * @return
     */
    private List<DimensionVo> getDimensions(String dimensions) {
        String[] dArr = StringUtils.split(dimensions, ",");
        List<DimensionVo> dimensionVoList=new ArrayList<>();
        for (int i=0;i<dArr.length;i+=2) {
            DimensionVo dimensionVo=new DimensionVo();
            dimensionVo.setKey(dArr[i]);
            dimensionVo.setValue(dArr[i+1]);
            dimensionVoList.add(dimensionVo);
        }
        return dimensionVoList;
    }
}
